import { options } from "./options";
import { getHead, loadImage } from "./loader";
import { lineConnector } from "./connector";
import store from "./store";
export class PNG {
  private chunks: Array<ArrayBuffer> = [];
  constructor(
    public width: number,
    public height: number,
    public itemHeight: number,
    public itemWidth: number
  ) {
    store.width = width;
    store.height = height;
    store.itemHeight = itemHeight;
    store.itemWidth = itemWidth;
    this.init();
  }
  private async init() {
    const signature = new Int8Array(options.PNG_SIGNATURE);
    this.chunks.push(signature);

    const header = await getHead(this.width, this.height);
    this.chunks.push(header);

    const lineNumber = Math.ceil(this.height / this.itemHeight);
    const colNumber = Math.ceil(this.width / this.itemWidth);
    store.imageList = Array.from({ length: lineNumber }, () =>
      Array.from({ length: colNumber })
    );
  }
  set(imageSrc: string | HTMLCanvasElement, line: number, col: number) {
    loadImage(imageSrc).then(res => {
      store.imageList[line][col] = res;
    });
    return this;
  }
  async get() {
    for (let i = 0; i < store.imageList.length; i++) {
      for (let j = 0; j < store.imageList[i].length; j++) {
        const image = store.imageList[i][j];
        if (!image) throw new Error("图像尚未加载完成");
      }
    }
    //获得每一行像素数据
    const rowDatas = [];
    for (let line = 0; line < store.imageList.length; line++) {
      const row = store.imageList[line];
      for (let y = 0; y < this.itemHeight; y++) {
        rowDatas.push(await lineConnector(row, y, this.width));
      }
    }
  }
}
export default getPNG;
